import cv2
 
class Camera:
    def __init__(self, device_id=0):
        self.cap = None
        self.device_id = device_id
 
    def open(self, device_id=1):
        """打开摄像头并设置参数，包含完整的异常处理"""
        try:
            if self.isOpened():
                print("摄像头已经开启...")
                return
 
            # 尝试打开摄像头设备
            self.cap = cv2.VideoCapture(device_id)
            if not self.cap.isOpened():
                raise ValueError(f"无法打开摄像头设备 {device_id}")
 
            # 设置捕获格式（添加异常捕获）
            try:
                self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G'))
            except cv2.error as e:
                print(f"警告：设置编码格式失败 - {str(e)}")
                print("尝试使用默认编码格式继续...")
 
            # 设置分辨率（添加范围检查）
            try:
                self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
                self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
            except cv2.error as e:
                print(f"警告：设置分辨率失败 - {str(e)}")
                print("尝试使用设备默认分辨率继续...")
 
            # 设置帧率（添加范围检查）
            try:
                self.cap.set(cv2.CAP_PROP_FPS, 30)
            except cv2.error as e:
                print(f"警告：设置帧率失败 - {str(e)}")
                print("尝试使用设备默认帧率继续...")
 
            # 设置白平衡（添加异常捕获）
            try:
                self.cap.set(cv2.CAP_PROP_WHITE_BALANCE_BLUE_U, 4000)
            except cv2.error as e:
                print(f"警告：设置白平衡失败 - {str(e)}")
                print("使用自动白平衡模式继续...")
 
            # 验证最终参数
            width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
            height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
            fps = self.cap.get(cv2.CAP_PROP_FPS)
            print(f"实际分辨率: {width}x{height}")
            print(f"实际帧率: {fps:.2f} fps")
 
        except Exception as e:
            print(f"摄像头初始化失败: {str(e)}")
            print("可能原因：")
            print("1. 摄像头设备未正确连接")
            print("2. 摄像头权限未开启")
            print("3. 设备号不正确（尝试修改device_id参数）")
            print("4. 摄像头被其他程序占用")
            self.release()
 
    def read(self):
        """读取帧时添加异常处理"""
        try:
            return self.cap.read()
        except cv2.error as e:
            print(f"读取帧失败: {str(e)}")
            return None, None
        except Exception as e:
            print(f"意外错误: {str(e)}")
            return None, None
 
    def release(self):
        """释放资源时添加异常处理"""
        try:
            if self.cap and self.cap.isOpened():
                print("释放摄像头资源...")
                self.cap.release()
        except Exception as e:
            print(f"释放资源时出错: {str(e)}")
        finally:
            self.cap = None
 
    def isOpened(self):
        """检查摄像头是否开启"""
        return self.cap is not None and self.cap.isOpened()
 
# 使用示例
if __name__ == "__main__":
    cam = Camera()
    cam.open()
    
    if cam.isOpened():
        ret, frame = cam.read()
        if ret:
            print("成功获取帧！")
            cv2.imshow('Camera', frame)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
        cam.release()
    else:
        print("摄像头初始化失败")